package com.googlecode.chigs.web.config.configuration;

import java.util.List;

import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.extensions.wizard.WizardStep;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.form.TextArea;
import org.apache.wicket.markup.html.form.TextField;
import org.apache.wicket.model.PropertyModel;
import org.apache.wicket.model.StringResourceModel;
import org.apache.wicket.spring.injection.annot.SpringBean;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.googlecode.chigs.domain.ConfigRevision;
import com.googlecode.chigs.domain.Product;
import com.googlecode.chigs.domain.Revision;
import com.googlecode.chigs.domain.Version;
import com.googlecode.chigs.repository.ChigsFacade;
import com.googlecode.chigs.web.doku.version.VersionSelector;

public class UpdateConfigurationStep extends WizardStep {
	private static Logger log = LoggerFactory.getLogger(UpdateConfigurationStep.class);

	@SpringBean
	private ChigsFacade chigs;

	public UpdateConfigurationStep(final ConfigRevision configRevision, Product product, final List<Revision> changes) {
		StringResourceModel label = new StringResourceModel("name.label", UpdateConfigurationStep.this, null);
		add(new Label("name.label", label));
		add(new TextField<String>("configRevision.configuration.name")
				.setRequired(true)
				.setLabel(label)
				.setEnabled(false));
		StringResourceModel descLabel = new StringResourceModel("description.label", UpdateConfigurationStep.this, null);
		add(new Label("description.label", descLabel));
		add(new TextArea<String>("configRevision.configuration.description")
				.setRequired(true)
				.setLabel(descLabel)
				.setEnabled(false));
		add(new Label("configRevision.nr"));

		add(new VersionSelector("version", new PropertyModel<Version>(configRevision, "version"), product) {
			@Override
			protected void onChange(AjaxRequestTarget target) {
				changes.clear();
				for (Revision revision : configRevision.getRevisions()) {
					revision.setConfigPairs(chigs.loadConfigPairsByRevision(revision));
					Revision latest = chigs.loadLatestRevision(revision.getModule());
					if (revision.getNr() != latest.getNr()) {
						latest.setConfigPairs(chigs.loadConfigPairsByRevision(latest));
						changes.add(latest);
						if (log.isDebugEnabled()) {
							log.debug("found new revision nr: " + latest.getNr() + " for module: " + revision.getModule());
						}
					}
				}
			}
		});
	}
}
